import React, { Component } from 'react';
import {sum} from './sum.js';
import './App.css';

class App extends Component {
  state = {
    number: '',
  }
  showPoint  = () => {
    try{
      var arr = JSON.parse(this.refs.myTextInput.value || '{}');
      if (Object.prototype.toString.call(arr) != '[object Array]' || arr.length <= 2) {
        this.setState({
          number: -1
        })
      } else {
        for (let i = 0;i<arr.length;i++){
          if (sum(arr.slice(0,i)) === sum(arr.slice(i+1))){
            this.setState({
              number: i,
            })
            break;
          } else {
            this.setState({
              number: -1,
            })
          }
        }
      }
    } catch(err) {
      this.setState({
        number: -1
      })
    }
  }
  render() {
    return (
      <div className="App">
        <div className="box">
          <input ref="myTextInput" className="input" placeholder="请输入一个数组" type="text"/>
          <input onClick={this.showPoint} className="button" type="button" value="平衡位" />
        </div>
        <div>平衡位是：{this.state.number}</div>
      </div>
    );
  }
}

export default App;
